﻿using System;
using System.IO;
using System.Xml;
using System.Windows.Forms;


namespace eRechnung
{
    // Diese Klasse dient als Parameter-Objekt für den Background Worker zum senden/empfangen des HTTP Request/Response

    public class ebInterfaceXMLSign
    {
       private string ViewState;
       private string eventVal;

       //public string postString { get; set; }
       // public bool rc;
       public enum RequestResult {undefined=0,OK, Cancelled, Error};
       public RequestResult Rc { get; set; }
       public enum RequestTarget { TestSystem = 0, ProductionSystem };
       private int _ReqestTarget;
       public RequestTarget Target
       {
           get
           {
               return (RequestTarget)_ReqestTarget;
           }
           set
           {
               _ReqestTarget = (int)value;
               request_url = test_url;
               if (value == RequestTarget.ProductionSystem)
               {
                   request_url = production_url;
               }
           }
       }
       private enum ExpectedType { Html, Xml };

       private string request_url;
       private const string test_url = @"https://test1.a-trust.at/https-security-layer-request/";
       private const string production_url = @"https://www.a-trust.at/mobile/https-security-layer-request/";

       public ebInterfaceXMLSign()
       {
           Target = RequestTarget.TestSystem;
       }

        /// <summary>
        /// Erstellt eine XMLDsig für das übergebene ebInterface XML Dokument 
        /// über den Handy Signatur Server der A-Trust
        /// </summary>
        /// <param name="xdoc1">
        /// zu signierendes ebInterface XML Dokument
        /// </param>
        /// <returns></returns>
       public XmlDocument SignXML(XmlDocument xdoc1)
       {
           bool preserve = true;
#if DEBUG && SAVE_HTML
           savehtml(xdoc1.InnerXml, "xdoc1AtEntry.xml");
#endif
           XmlDocument xmlrq = new XmlDocument();
           xmlrq.PreserveWhitespace = true;
           string StrXmlSignReq = "";
           StrXmlSignReq = Globals.ThisDocument.GetFromXMLResource(InvoiceXML.XMLSignRequest);
           xmlrq.LoadXml(StrXmlSignReq);
           XmlNamespaceManager xqrMgr = new XmlNamespaceManager(xmlrq.NameTable);
           string Prefix_sl = "http://www.buergerkarte.at/namespaces/securitylayer/1.2#";
           xqrMgr.AddNamespace("sl", Prefix_sl);
           XmlNode xn = xmlrq.SelectSingleNode("//sl:XMLContent", xqrMgr);
           // string ebInterfaceDoc = String.Empty;
           // da ist was zu tun ....
           XmlDocument xdoc2 = new XmlDocument();
           xdoc2.PreserveWhitespace = true;
           xdoc2 = InvoiceXML.BeautifyXml(xdoc1);
#if DEBUG && SAVE_HTML
           savehtml(xdoc2.InnerXml, "xdoc2.xml");
#endif
           XmlNamespaceManager ebMgr = new XmlNamespaceManager(xdoc2.NameTable);
           ebMgr.AddNamespace("eb", InvoiceXML.PrefixURLeb);
           ebMgr.AddNamespace("dsig", InvoiceXML.PrefixURLsig);
           XmlNode xeb = xdoc2.SelectSingleNode("eb:Invoice", ebMgr);
           xn.InnerXml = xeb.OuterXml;
           string toSend = xmlrq.OuterXml;
#if DEBUG && SAVE_HTML
           savehtml(toSend, "toSend.xml");
#endif
           string xmlPage="";
           DlgWebSign WebSign = new DlgWebSign();
           DialogResult rc;
           WebSign.Xmlrequest = toSend;
           WebSign.Target = Target;
           rc=WebSign.ShowDialog();
           if (rc==DialogResult.Cancel)
           {
               WebSign.Dispose();
               MessageBox.Show("Handy Signatur abgebrochen.");
               return null;
           }
           xmlPage = WebSign.Xmlresult;
           WebSign.Close();
           WebSign.Dispose();
           if (xmlPage.IndexOf("sl:ErrorResponse")>0)
           {
               throw new Exception("Fehler bei Handy Signatur:\r\n"+GetErrorResponse(xmlPage));
           }
           #region Signierte Rechnung zurückgeben
           XmlDocument xdoc = new XmlDocument();
           xdoc.PreserveWhitespace = preserve;
           xdoc.LoadXml(xmlPage);
           
           XmlElement root = xdoc.DocumentElement;
#if DEBUG && SAVE_HTML
           savehtml(root.InnerXml, "rootOfPage3.xml");
#endif
           XmlDocument signedDoc = new XmlDocument();
           signedDoc.PreserveWhitespace = true;
           signedDoc.LoadXml(root.InnerXml);
#if DEBUG && SAVE_HTML
           savehtml(signedDoc.OuterXml, "signedDOC.xml");
#endif
           #endregion

           return signedDoc;
       }
       private string GetErrorResponse(string xmlerror)
       {
           string resp = String.Empty;
           XmlDocument xdoc = new XmlDocument();
           xdoc.PreserveWhitespace = true;
           xdoc.LoadXml(xmlerror);
           XmlNamespaceManager xqrMgr = new XmlNamespaceManager(xdoc.NameTable);
           string Prefix_sl = "http://www.buergerkarte.at/namespaces/securitylayer/1.2#";
           xqrMgr.AddNamespace("sl", Prefix_sl);
           XmlNode xn = xdoc.SelectSingleNode("/sl:ErrorResponse/sl:ErrorCode", xqrMgr);
           string ErrCode = "";
           if (xn != null)
           {
               ErrCode = xn.InnerText;
           }
           xn = xdoc.SelectSingleNode("/sl:ErrorResponse/sl:Info", xqrMgr);
           string Info = "";
           if (xn != null)
           {
               Info = xn.InnerText;
           }
           resp = "ErrorCode=" + ErrCode + "\r\nInfo=" + Info;
           return resp;
       }

#if DEBUG && SAVE_HTML
       public void savehtml(string html, string pagename)
       {
           StreamWriter ofile = File.CreateText(pagename);
           ofile.Write(html);
           ofile.Close();

       }
#endif
       #region Webrequests
       #endregion
    }
}
